<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备ID" prop="equipmentUid">
        <el-input
          v-model="queryParams.equipmentUid"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备类型" prop="equipmentType">
        <el-select v-model="queryParams.equipmentType" placeholder="请选择">
          <el-option
            v-for="item in equipmentTypes"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="检测状态" prop="detectionState">
        <el-select v-model="queryParams.detectionState" placeholder="请选择">
          <el-option
            v-for="item in detectionStates"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="保管单位" prop="equipmentOwner">
        <el-input
          v-model="queryParams.equipmentOwner"
          placeholder="请输入保管单位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>

      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['equipment:book:add']"-->
<!--        >新增-->
<!--        </el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['equipment:book:edit']"-->
<!--        >修改-->
<!--        </el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['equipment:book:remove']"-->
<!--        >删除-->
<!--        </el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button  size="mini" @click="songjian">送检</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bookList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" width="55" align="center" prop="id"/>
      <el-table-column label="设备ID" align="center" prop="equipmentUid"/>
      <el-table-column label="设备类型" align="center" prop="equipmentType"/>
      <el-table-column label="监测状态 已超期/未超期/已送检" align="center" prop="detectionState"/>
      <el-table-column label="上次检测时间" align="center" prop="lastDetectionDay" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastDetectionDay, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下次检测时间" align="center" prop="nextDetectionDay" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.nextDetectionDay, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划送检日期" align="center" prop="planDetectionDay" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planDetectionDay, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="保管单位" align="center" prop="equipmentOwner"/>
      <el-table-column min-width="200" fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="openUploadReport(scope.row)"

            :disabled="scope.row.detectionState!='已送检'"
          >上传报告
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="doGetReport(scope.row)"
          >校验记录
          </el-button>

          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-edit"-->
          <!--            @click="handleUpdate(scope.row)"-->
          <!--            v-hasPermi="['equipment:book:edit']"-->
          <!--          >修改-->
          <!--          </el-button>-->
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-delete"-->
          <!--            @click="handleDelete(scope.row)"-->
          <!--            v-hasPermi="['equipment:book:remove']"-->
          <!--          >删除-->
          <!--          </el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备台账维护对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="${comment}" prop="equipmentId">
          <el-input v-model="form.equipmentId" placeholder="请输入${comment}"/>
        </el-form-item>
        <el-form-item label="监测状态 已超期/未超期/已送检" prop="detectionState">
          <el-input v-model="form.detectionState" placeholder="请输入监测状态 已超期/未超期/已送检"/>
        </el-form-item>
        <el-form-item label="上次检测时间" prop="lastDetectionDay">
          <el-date-picker clearable
                          v-model="form.lastDetectionDay"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择上次检测时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="下次检测时间" prop="nextDetectionDay">
          <el-date-picker clearable
                          v-model="form.nextDetectionDay"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择下次检测时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划送检日期" prop="planDetectionDay">
          <el-date-picker clearable
                          v-model="form.planDetectionDay"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择计划送检日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="保管单位" prop="equipmentOwner">
          <el-input v-model="form.equipmentOwner" placeholder="请输入保管单位"/>
        </el-form-item>
        <el-divider content-position="center">${subTable.functionName}信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddEquipment">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteEquipment">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="equipmentList" :row-class-name="rowEquipmentIndex"
                  @selection-change="handleEquipmentSelectionChange" ref="equipment">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="$comment" prop="equipmentUid" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.equipmentUid" placeholder="请输入$comment"/>
            </template>
          </el-table-column>
          <el-table-column label="$comment" prop="equipmentTypeId" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.equipmentTypeId" placeholder="请输入$comment"/>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!--    上传报告对话框-->
    <el-dialog title="上传报告" :visible.sync="uploadReportOpen" width="800px" append-to-body>
      <el-form ref="form" :model="uploadReportFrom" :rules="uploadReportFormRules" label-width="80px">

        <el-row>
          <el-col :span="10">
            <el-form-item label="校验时间" prop="detectionTime">
              <el-date-picker clearable
                              v-model="uploadReportFrom.detectionTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择校验时间">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="14">
            <el-form-item label-width="100px" label="校验证书编号" prop="detectionCertCode">
              <el-input v-model="uploadReportFrom.detectionCertCode" placeholder="请输入校验证书编号"/>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item label="校验单位" prop="detectionCompany">
              <el-input  v-model="uploadReportFrom.detectionCompany" placeholder="请输入校验单位"/>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item label="校验人员" prop="detectionPeople">
              <el-input  v-model="uploadReportFrom.detectionPeople" placeholder="请输入校验人员"/>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item label="校验结论" prop="detectionResult">
              <el-input v-model="uploadReportFrom.detectionResult" placeholder="请输入校验结论"/>
            </el-form-item>
          </el-col>
        </el-row>


        <el-form-item label="校验报告" prop="detectionCertCode">
          <el-upload
            class="upload-demo"
            action="#"
            :limit="1"
            :file-list="reportFileList"
            :on-change="uploadReportFileChange"
            :auto-upload="false"
          >
            <el-button size="small" type="primary">上传报告</el-button>

          </el-upload>

        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doUploadReport">上 传</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="校验记录" :visible.sync="detectionRecordOpen" width="800px" append-to-body>


      <el-table v-loading="loading" :data="detectionRecords" >

        <el-table-column label="校验时间"  align="center" prop="detectionTime"/>
        <el-table-column label="校验证书编号" align="center" prop="detectionCertCode"/>
        <el-table-column label="校验单位" align="center" prop="detectionCompany"/>
        <el-table-column label="校验人员" align="center" prop="detectionPeople"/>
        <el-table-column label="校验结论" align="center" prop="detectionResult"/>
        <el-table-column min-width="200" fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="downloadReportFile(scope.row)"
            >下载
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="openUploadReport(scope.row)"
            >修改
            </el-button>

          </template>
        </el-table-column>
      </el-table>


    </el-dialog>

  </div>
</template>

<script>
import {listBook, getBook, delBook, addBook, updateBook} from "@/api/equipment/book";
import {listType} from "@/api/equipment/type";
import {addReport, doDownloadReportFile, downloadReportFile, getReport, listReport} from "@/api/equipment/report";

export default {
  name: "Book",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedEquipment: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备台账维护表格数据
      bookList: [],
      // ${subTable.functionName}表格数据
      equipmentList: [],
      // 校验记录表格数据
      detectionRecords: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      uploadReportOpen: false,
      detectionRecordOpen:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        equipmentId: null,
        equipmentUid: null,
        equipmentType: null,
        detectionState: null,
        lastDetectionDay: null,
        nextDetectionDay: null,
        planDetectionDay: null,
        equipmentOwner: null
      },
      // 表单参数
      form: {},
      //上传报告的表单
      uploadReportFrom: {
        equipmentId: null,
        detectionTime: null,
        detectionCertCode: null,
        detectionCompany: null,
        detectionPeople:null,
        detectionResult: null,
        reportFile: null,
      },
      //上传报告的表单的文件列表
      reportFileList: [],
      // 表单校验
      rules: {},
      uploadReportFormRules: {
        detectionTime: [
          { required: true, message: '请输入校验时间', trigger: 'blur' },
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        detectionCertCode: [
          { required: true, message: '请输入证书编号', trigger: 'blur' },
        ],
        detectionCompany: [
          { required: true, message: '请输入校验公司', trigger: 'blur' },
        ],
        detectionPeople: [
          { required: true, message: '请输入校验人', trigger: 'blur' },
        ],
        detectionResult: [
          { required: true, message: '请输入校验结果', trigger: 'blur' },
        ],
        reportFile: [
          { required: true, message: '请选择校验报告', trigger: 'blur' },

        ],
      },
      equipmentTypes: [],
      detectionStates: [
        {
          value: '已超期',
          label: '已超期',
        },
        {
          value: '未超期',
          label: '未超期',
        },
        {
          value: '已送检',
          label: '已送检',
        },
      ]
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询设备台账维护列表 */
    getList() {
      this.loading = true;
      listBook(this.queryParams).then(response => {
        this.bookList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      listType().then(response => {
        this.equipmentTypes = response.rows.map(type => {
          return {
            value: type.id,
            label: type.equipmentName
          }
        });

      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.uploadReportOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        equipmentId: null,
        detectionState: null,
        lastDetectionDay: null,
        nextDetectionDay: null,
        planDetectionDay: null,
        equipmentOwner: null
      };
      this.uploadReportFrom = {

        equipmentId: null,
        detectionTime: null,
        detectionCertCode: null,
        detectionCompany: null,
        detectionResult: null,
        reportFile: null,

      }
      this.reportFileList = []
      this.equipmentList = [];
      this.resetForm("form");
    },
    uploadReportFileChange(file, fileList) {

      this.uploadReportFrom.reportFile = file.raw

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    songjian(row) {
      const ids = row.id || this.ids;
      let promises = []
      ids.forEach((id) => {
        promises.push(updateBook({
          id: id,
          detectionState: '已送检'
        }))

      })
      Promise.all(promises).then(() => {
        this.getList()
        this.$modal.msgSuccess("送检成功");
      })


    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备台账维护";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBook(id).then(response => {
        this.form = response.data;
        this.equipmentList = response.data.equipmentList;
        this.open = true;
        this.title = "修改设备台账维护";
      });
    },

    /** 打开上传报告的表单 */
    openUploadReport(row) {
      const id = row.id || this.ids
      this.uploadReportFrom.equipmentId = id
      this.uploadReportOpen = true

    },
    /** 下载校验报告文件 */
    downloadReportFile(row) {
      const id = row.id || this.ids
      doDownloadReportFile(id)

    },
    /** 上传报告 */
    doUploadReport() {
      if(this.uploadReportFrom.reportFile==null){
        this.$modal.msgWarning("请选择校验报告文件!");
        return
      }
      addReport(this.uploadReportFrom).then(() => {
        this.uploadReportOpen = false
        this.$modal.msgSuccess("校验报告上传成功!!");
        this.reset();
      })

    },
    /** 获取校验记录 */
    doGetReport(row) {

      const id = row.id || this.ids

      listReport({
        equipmentId:row.equipmentId
      }).then(response => {

        this.detectionRecords = response.rows;
        this.detectionRecordOpen = true


      });

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.equipmentList = this.equipmentList;
          if (this.form.id != null) {
            updateBook(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBook(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除设备台账维护编号为"' + ids + '"的数据项？').then(function () {
        return delBook(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** ${subTable.functionName}序号 */
    rowEquipmentIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** ${subTable.functionName}添加按钮操作 */
    handleAddEquipment() {
      let obj = {};
      obj.equipmentUid = "";
      obj.equipmentTypeId = "";
      this.equipmentList.push(obj);
    },
    /** ${subTable.functionName}删除按钮操作 */
    handleDeleteEquipment() {
      if (this.checkedEquipment.length == 0) {
        this.$modal.msgError("请先选择要删除的${subTable.functionName}数据");
      } else {
        const equipmentList = this.equipmentList;
        const checkedEquipment = this.checkedEquipment;
        this.equipmentList = equipmentList.filter(function (item) {
          return checkedEquipment.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleEquipmentSelectionChange(selection) {
      this.checkedEquipment = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('equipment/book/export', {
        ...this.queryParams
      }, `book_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
